<template>
  <div class="back" style=" height: calc(100vh - 100px)">

    <div style="display: flex;justify-content: center;margin-bottom: 20px;padding-top: 100px">
      <span style="color: red;font-size: 20px;background-color: #f3f3f3;padding: 10px 20px;border-radius: 20px">收货信息</span>
    </div>

    <div style="width: 75%;margin: 0 auto;padding: 20px;background-color: white;border-radius: 20px">

      <el-table v-loading="loading"
                :row-class-name="tableRowClassName"
                header-cell-class-name="header-name"
                :data="userlist">

        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="手机" align="center" prop="userPhone" />
        <el-table-column label="地址" align="center" prop="userAddr" show-overflow-tooltip/>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
            >修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="收货信息" :visible.sync="open2" width="50%" append-to-body>
      <el-form ref="form" :model="myinfo"  label-width="90px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="myinfo.userName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="手机" prop="userPhone">
          <el-input v-model="myinfo.userPhone" placeholder="请输入手机"/>
        </el-form-item>
        <el-form-item label="地址" prop="userAddr">
          <el-input v-model="myinfo.userAddr" placeholder="请输入地址"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="open2 =false">取 消</el-button>
      </div>
    </el-dialog>


    <div style="height: 50px;"></div>

    <div style="display: flex;justify-content: center;margin-bottom: 20px">
      <span style="color: red;font-size: 20px;background-color: #f3f3f3;padding: 10px 20px;border-radius: 20px">我的购物车</span>
    </div>


    <div style="width: 75%;margin: 0 auto;padding: 20px;background-color: white;border-radius: 20px">

      <el-table v-loading="loading" :data="cartList"
                :row-class-name="tableRowClassName"
                header-cell-class-name="header-name"
                @selection-change="selectionChange" :row-key="getRowKeys"
      >
        <el-table-column type="selection" width="50" align="center"  />
        <el-table-column label="名称" align="center" prop="goodsInfo.goodsName" show-overflow-tooltip/>
        <el-table-column label="图片" align="center" prop="goodsInfo.goodsPic" width="160">
          <template slot-scope="scope">
            <div v-if="!scope.row.goodsInfo.goodsPic">暂无图像</div>
            <div v-else>
              <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.goodsInfo.goodsPic.split(',')[0]"
                  :preview-src-list="scope.row.goodsInfo.goodsPic.split(',')">
              </el-image>
            </div>

          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="goodsInfo.goodsInfo" width="180" show-overflow-tooltip/>
        <el-table-column label="价格" align="center" prop="goodsInfo.goodsPrice"/>
        <el-table-column label="库存" align="center" prop="goodsInfo.goodsNum"/>
        <el-table-column label="数量" align="center" prop="cartNum">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.cartNum" @change="handleChange" :min="1" :max="scope.row.goodsInfo.goodsNum*1" ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="text-align: right;margin:30px 100px 30px 0;">

      <span style="color: red;font-size: 20px;background-color: #f3f3f3;padding: 10px 20px;border-radius: 20px"> 总价： {{totalprice}}</span>

    </div>
    <div style="text-align: right;margin:30px 100px 30px 0;">
      <el-button type="danger"   @click="buy">确认购买</el-button>
    </div>




    <el-dialog :title="'商品支付：￥'+totalprice" :visible.sync="open" width="38%" append-to-body>
      <el-form ref="payform" :model="payform"  label-width="180px">
        <el-form-item >
          <el-radio-group v-model="payform.paymentMethod">
            <el-radio label="微信">微信</el-radio>
            <el-radio label="支付宝">支付宝</el-radio>
            <el-radio label="信用卡">信用卡</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div style="display: flex;justify-content: center;text-align: center;">
        <div>
          <div style="font-size: 20px;margin-bottom: 20px">
            <div v-if="payform.paymentMethod=='微信'">
              请使用微信扫码支付
            </div>
            <div v-if="payform.paymentMethod=='支付宝'">
              请使用支付宝扫码支付
            </div>
            <div v-if="payform.paymentMethod=='信用卡'">
              请使用信用卡app扫码支付
            </div>
          </div>

          <el-image
              style=" height: 300px"
              :src="paypng"
              :preview-src-list="[paypng]">
          </el-image>
        </div>


      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open =false">取 消</el-button>
      </div>
    </el-dialog>



  </div>



</template>

<script>
import {listCart, getCart, delCart, addCart, updateCart} from "@/api/project/cart";
import {listOrders, getOrders, delOrders, addOrders, updateOrders} from "@/api/project/orders";
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/project/goods";
import paypng from "../../assets/pay.png"
export default {
  name: "index",
  data() {
    return {
      paypng:paypng,
      payform:{
        paymentMethod:"微信"
      },
      myinfo:{},
      userlist:[],
      cartList:[],
      loading:false,
      total:0,
      totalprice:0,
      selectdata:[],
      open:false,
      open2:false,
    }
  },

  created() {
    this.getList();
    this.getUser()
  },

  methods: {
    getUser(){
      console.log(JSON.parse(localStorage.getItem('userInfo')))
      const user = JSON.parse(localStorage.getItem('userInfo'))
      this.myinfo.userName = user.userNickname
      this.myinfo.userPhone = user.userPhone
      this.myinfo.userAddr = user.userAddr
      this.userlist[0] = this.myinfo;
    },
    submitForm(){
      let data={
        userId:JSON.parse(localStorage.getItem("userInfo")).id,
        ordersGoods:JSON.stringify(this.selectdata),
        userName:this.myinfo.userName,
        userPhone:this.myinfo.userPhone,
        userAddr:this.myinfo.userAddr,
        ordersStatus:"未发货",
        orderType:"商品",
        orderId:"order_"+new Date().getTime()
      }
      addOrders(data).then(res => {
        const promises = this.selectdata.map(item => {
          delCart(item);
          return getGoods(item.goodsInfo).then(res2 => {
            res2.data.goodsNum = res2.data.goodsNum * 1 - item.cartNum * 1;
            return updateGoods(res2.data);
          });
        });

        Promise.all(promises).then(() => {
          this.$message.success("购买成功！");
          this.open = false;
          this.$router.push({ path: '/orders'});
        }).catch(error => {
          console.error('Error:', error);
        });
      });


    },
    handleUpdate(){

      this.myinfo = this.userlist[0];
      this.open2 = true;
    },
    submitForm2(){
      if(!this.myinfo.userName){
        this.$message.error("请填写完全收货信息！");
        return
      }
      if(!this.myinfo.userPhone){
        this.$message.error("请填写完全收货信息！");
        return
      }
      if(!this.myinfo.userAddr){
        this.$message.error("请填写完全收货信息！");
        return
      }
      this.userlist[0]=this.myinfo
      this.open2=false
    },
    buy(){
      if(!this.myinfo.userName){
        this.$message.error("请填写完全收货信息！");
        return
      }
      if(!this.myinfo.userPhone){
        this.$message.error("请填写完全收货信息！");
        return
      }
      if(!this.myinfo.userAddr){
        this.$message.error("请填写完全收货信息！");
        return
      }

      if(this.selectdata.length>0){
        this.open=true
      }else {
        this.$message.error("请选择所需结算的购物车商品信息");
      }
    },
    sumprice(row){
      let totalprice=0
      row.forEach(res=>{
        totalprice +=res.cartNum*res.goodsInfo.goodsPrice
      })
      this.totalprice =totalprice
    },
    selectionChange(selection) {
      this.selectdata=selection
      this.sumprice(selection)


    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex %2 == 1) {
        console.log(111)
        return 'warning-row';
      } else  {
        console.log(222)
        return 'success-row';
      }

    },
    getRowKeys(row) {
      return row.id;
    },
    handleChange(value) {
      this.sumprice(this.selectdata)
    },
    /** 查询购物车列表 */
    getList() {
      this.loading = true;
      listCart().then(response => {
        let data = response.data.filter(data => data.userId==JSON.parse(localStorage.getItem("userInfo")).id );

        this.cartList = data;
        this.total = data.length;
        this.loading = false;
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除？').then(function () {
        return delCart(row);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
  }
}
</script>

<style>
.back{
  background-image: url('../../assets/bg.png');
  background-size: cover;
}
.el-table .warning-row {
  background: #fcf2e6;
  font-size: 20px;
  color: black;
}
/*.el-table__body tr{

  pointer-events: none;

}*/
.el-table .success-row {
  background: #f8d6ba;
  font-size: 20px;
  color: black;
}


.header-name {
  font-size: 20px;
  color: black;
}
</style>
